/**
 * 创建websocket连接，提供相关函数的封装
 */ 

var Sock = {
	init_index:0,
	ws:null,
	opt:{
		url:"",
		log:function(id,message,title,error,ct){
			var consoleobj = $('#layer_console')[0];
			var errorclass = "";
			var btnclass = " btn-success";
			if(error) errorclass = ' error',btnclass = " btn-danger";
			var stit = title ? title : '运行消息';
			
			//隐藏进行中标识
			$('div.console_title:contains("'+stit+'")').parent('.panel-heading').siblings('.console_content').find("dot").hide();
			
			//var ms = '<div class="console_msg animated fadeInDown clearfix'+errorclass+'">';
			//<a class="pull-right btn btn-default btn-sm"><i class="fa fa-gear"></i></a>
			var ms = '<div class="panel console_msg animated fadeInRight clearfix'+errorclass+'">';
			if(stit){
				/*
				 ms += '<div class="console_title"><i class="fa fa-paw"></i>&nbsp;&nbsp;'+title+
				'<div class="btn-group pull-right" role="group">'+
				    '<button type="button" class="btn'+btnclass+' dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'+
				      '<i class="fa fa-gear"></i>'+
				    '</button>'+
				    '<ul class="dropdown-menu">'+
				        '<li><a href="javascript:void(0);" onclick="$(\'#layer_console .error\').remove();">删除错误消息</a></li>'+
				        '<li><a href="javascript:void(0);" onclick="$(\'#layer_console .console_msg\').not(\'.error\').remove();">删除正确消息</a></li>'+
				        '<li><a href="javascript:void(0);" onclick="$(\'#layer_console .console_msg\').remove();">清空消息</a></li>'+
				    '</ul>'+
				  '</div>'+
				'</div>';
				 */
				ms += '<div class="panel-heading">'+
				'<div class="panel-control">'+
					'<div class="btn-group">'+
						'<button class="dropdown-toggle btn" data-toggle="dropdown" aria-expanded="false">'+
							'<i class="fa fa-cogs"></i>'+
						'</button>'+
						'<ul class="dropdown-menu dropdown-menu-right">'+
							'<li><a href="javascript:void(0);" onclick="$(\'#layer_console .error\').remove();">删除错误消息</a></li>'+
							'<li><a href="javascript:void(0);" onclick="$(\'#layer_console .console_msg\').not(\'.error\').remove();">删除正确消息</a></li>'+
							//'<li class="divider"></li>'+
							'<li><a href="javascript:void(0);" onclick="$(\'#layer_console .console_msg\').remove();">清空消息</a></li>'+
						'</ul>'+
					'</div>'+
				'</div>'+
				'<div class="panel-title console_title">'+stit+'</div>'+
			'</div>';
			}
			//ms += '<p class="console_content">'+message+'</p>';
			ms += '<div class="panel-body console_content">'+message+'</div>';
			if(ct){
				ms += '<div class="panel-footer">'+ct+'</span></div>';
			}else{
				var dt = new Date();
				ms += '<div class="panel-footer">'+dt.toLocaleString()+'</span></div>';
			}
			$(consoleobj).prepend(ms);
			
			if($(consoleobj).children().length){
				while ($(consoleobj).children().length > 50) {  
					//超过50条消息之后删除最早一条消息
	                consoleobj.removeChild(consoleobj.lastChild);  
	            }  
			}
			
            consoleobj.scrollTop = 0;
            
            //$.niftyAside('show');
            
		},//日志输出
		onOpen:function(evnt){
			
			//console.info(evnt);
			
		},//连接成功之后
		onMessage:function(evnt){},//收到服务器推送的消息时
		onError:function(evnt){},
		onClose:function(evnt){},
	},
	/**
	 * 实例化基础信息
	 * 
	 * @param cfg
	 */
	init:function(cfg){
		
		// 获取配置
		for (c in cfg) {
			this.opt[c] = cfg[c];
		}
		if(userId){
			//Pace.ignore(function(){
			this.ws = new SockJS(this.opt.url,undefined,{"sessionId":function(){return userId;}});
			this.connect();
			//})
		}
	},
	/**
	 * 发起连接
	 */
	connect:function(){
		//var sock = this;
		//复制提取配置信息
		var option = this.opt;
		//连接成功之后
		this.ws.onopen = function (evnt) {
			this.init_index = 0;
			//option.log('','Info:'+option.url+' connection opened.');  
			option.onOpen(evnt);
        };
        //收到服务器推送的消息时
        this.ws.onmessage = function (evnt) {
        	this.init_index = 0;
        	option.onMessage(evnt);
        };
        //发送错误
        this.ws.onerror = function (evnt) {
        	option.onError(evnt);
        	console.info('','Error:'+option.url+' ' + evnt.data);  
        };
        //关闭连接之后
        this.ws.onclose = function (evnt) {
        	//console.info('连接关闭,进行3次重连。。。');
        	option.onClose(evnt);
        	Sock.ws = null;
			Sock.reconnect();
        	//option.log('','Info:'+option.url+' connection closed.');
        	//option.log('','连接关闭！');
        }
	},
	reconnect:function(dataa){
		//已经连接成功
		if(Sock.ws && Sock.ws.readyState == 1){
			Sock.init_index = 0;
			return false;
		}
		//console.info(init_index);
		if(this.init_index >= 3){
			Sock.init_index = 0;
			console.info("Websocket 重连失败！");
			return false;
		}
		this.init_index++;
		//initSock();
		setTimeout(function(){
			console.info("Websocket 重连，第"+Sock.init_index+'次');
			Sock.init();
			//debugger
			if(dataa && Sock.ws.readyState == 0){
			setTimeout(function(){
				Sock.messageSend(dataa);
			},1000);
			}
		},(this.init_index - 1) * 1000);
		
		return true;
	},
	/**
	 * 发消息
	 */
	messageSend:function(dataa){
		if(top.Pace) top.Pace.stop();;
		//debugger
//		var rec = false;
//		if (this.ws == null || Sock.ws.readyState != 1) {
//			Sock.init_index = 0;
//			rec = Sock.reconnect();
//		}
		//禁用进度条
		//Pace.ignore(function(){
			if (this.ws != null && Sock.ws.readyState == 1) {
				dataa['userId'] = 123;
				var msg = JSON.stringify(dataa);
	            //var message = document.getElementById('message').value;  
	            //this.opt.log('',msg);  
	            this.ws.send(msg);  
	            this.init_index = 0;
			} else {
				if(this.init_index <= 3){
		        	//Sock.init_index = 0;
		        	Sock.reconnect(dataa);
				}
	            //console.info('connection not established, please connect.');  
	        } 
		//})
		/*
		if (this.ws != null && Sock.ws.readyState == 1) {
			dataa['userId'] = userId;
			var msg = JSON.stringify(dataa);
            //var message = document.getElementById('message').value;  
            //this.opt.log('',msg);  
            this.ws.send(msg);  
            this.init_index = 0;
        } else {
        	Sock.init_index = 0;
        	Sock.reconnect();
            //console.info('connection not established, please connect.');  
        } 
        */
	},
	callback:function(obj){
		
		if(obj.error){
			toast.warning(obj.message,'提示');
		}else{
			toast.success(obj.message,'提示');
		}
		
	},
	/**
	 * 关闭连接
	 */
	disconnect:function(){
		if (this.ws != null) {  
			this.ws.close();  
			this.ws = null;  
        }
	},
	findElement: function(sele){
		//全局查找元素
	    	var obj = [];
	    	$(top.document).find("iframe").each(function(){ 
	    		var bd = this.contentWindow.document;//.body; 
	    		if($(bd).find(sele).length){
	    			obj.push($(bd).find(sele));
	    		}
	    	})
			//console.info(obj); 
	    	return obj;
	 },
	 freshGridElement: function (sele){
	    	//刷新grid
	    	$(top.document).find("iframe").each(function(){ 
	    		var bd = this.contentWindow.document;//.body; 
	    		if($(bd).find(sele).length){
	    			console.info(this.contentWindow.$(sele));
	    			this.contentWindow.$(sele).grid('load');
	    		}
	    	})
	    	
	 }
};